// utils/http.util.js
import { generateSignature } from './sign.util'

class HttpUtil {
    static baseURL = '/api'
    static appId = 'wep-client'
    static defaultHeaders = {
        'Content-Type': 'application/json'
    }

    static async request(method, endpoint, data = null) {
        const url = this.baseURL + endpoint
        const timestamp = Date.now().toString()

        // 注意 body 可能为空
        const bodyData = method !== 'GET' && data ? JSON.stringify(data) : ''
        const signature = generateSignature(this.appId, timestamp)

        const config = {
            method,
            headers: {
                ...this.defaultHeaders,
                'X-App-Id': this.appId,
                'X-Timestamp': timestamp,
                'X-Signature': signature
            }
        }

        if (bodyData) {
            config.body = bodyData
        }

        try {
            const response = await fetch(url, config)
            return this.handleResponse(response)
        } catch (error) {
            return this.handleError(error)
        }
    }

    static async handleResponse(response) {
        if (!response.ok) {
            const error = new Error(`HTTP 错误 ${response.status}`)
            error.status = response.status
            try {
                error.data = await response.json()
            } catch {
                error.data = await response.text()
            }
            throw error
        }
        return response.json()
    }

    static handleError(error) {
        // 统一处理网络错误
        const enhancedError = new Error(error.message || '网络请求失败')
        enhancedError.isNetworkError = !error.status
        throw enhancedError
    }

    static get(endpoint, params) {
        const query = new URLSearchParams(params).toString()
        return this.request('GET', query ? `${endpoint}?${query}` : endpoint)
    }

    static post(endpoint, data) {
        return this.request('POST', endpoint, data)
    }

    static put(endpoint, data) {
        return this.request('PUT', endpoint, data)
    }

    static deleteById(endpoint, id) {
        return this.request('DELETE', `${endpoint}/${id}`)
    }

    static deleteBatch(endpoint, ids) {
        return this.request('DELETE', endpoint, ids)
    }

    static async download(endpoint) {
        const url = this.baseURL + endpoint
        const timestamp = Date.now().toString()
        const signature = generateSignature(this.appId, timestamp)

        const config = {
            method: 'GET',
            headers: {
                'X-App-Id': this.appId,
                'X-Timestamp': timestamp,
                'X-Signature': signature
                // 注意：不要设置 Content-Type 为 application/json！
            }
        }

        try {
            const response = await fetch(url, config)
            if (!response.ok) {
                const error = new Error(`下载失败：HTTP ${response.status}`)
                throw error
            }
            return response.blob()  // 👈 正确方式
        } catch (error) {
            throw new Error(error.message || 'PDF 下载失败')
        }
    }


    // 可以继续添加 put、delete 等其他方法
}

export default HttpUtil